package top.lvkun.order.service.impl;

import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.lvkun.basic.constant.Constant;
import top.lvkun.basic.service.impl.BaseServiceImpl;
import top.lvkun.basic.utils.AjaxResult;
import top.lvkun.basic.utils.CodeGenerateUtils;
import top.lvkun.order.domain.AdoptOrder;
import top.lvkun.order.domain.OrderAddress;
import top.lvkun.order.mapper.AdoptOrderMapper;
import top.lvkun.order.mapper.OrderAddressMapper;
import top.lvkun.order.service.IAdoptOrderService;
import top.lvkun.pay.domain.PayBill;
import top.lvkun.pay.mapper.PayBillMapper;
import top.lvkun.pay.service.IAlipayService;
import top.lvkun.pet.domain.Pet;
import top.lvkun.pet.mapper.PetMapper;
import top.lvkun.quartz.domain.QuartzJobInfo;
import top.lvkun.quartz.job.CancelOrderJob;
import top.lvkun.quartz.service.IQuartzService;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@SuppressWarnings("ALL")
@Service
public class AdoptOrderServiceImpl extends BaseServiceImpl<AdoptOrder> implements IAdoptOrderService {

    @Autowired
    private OrderAddressMapper orderAddressMapper;
    @Autowired
    private AdoptOrderMapper adoptOrderMapper;
    @Autowired
    private PetMapper petMapper;
    @Autowired
    private PayBillMapper payBillMapper;
    @Autowired
    private IAlipayService alipayService;
    @Autowired
    private IQuartzService quartzService;


    /**
     * 前台：用户领养宠物提交订单
     * @param adoptOrder
     * @return
     */
    @Override
    @Transactional
    public AjaxResult submitAdoptOrder(AdoptOrder adoptOrder) {
        //1.利用工具类生成订单编号
        String orderSn = CodeGenerateUtils.generateOrderSn(adoptOrder.getUser().getId());

        //2.保存OrderAddress数据，设置订单编号，返回主键
        OrderAddress orderAddress = adoptOrder.getOrderAddress();
        orderAddress.setOrderSn(orderSn);
        orderAddressMapper.save(orderAddress);

        //3.保存AdoptOrder数据，返回主键
        adoptOrder.setShop_id(adoptOrder.getPet().getShop_id());
        adoptOrder.setAddress_id(orderAddress.getId());
        adoptOrder.setDigest("【领养订单】" + adoptOrder.getUser().getUsername() + " 领养了 " + adoptOrder.getPet().getName());
        adoptOrder.setPrice(adoptOrder.getPet().getSaleprice());
        adoptOrder.setOrderSn(orderSn);
        //最迟支付时间：设置为15分钟
        Date lastPayTime = DateUtils.addMinutes(new Date(), 15);
        adoptOrder.setLastPayTime(lastPayTime);
        adoptOrderMapper.save(adoptOrder);

        //4.修改OrderAddress的外键order_id
        orderAddress.setOrder_id(adoptOrder.getId());
        orderAddressMapper.update(orderAddress);

        //5.修改宠物状态为已下架，并设置购买人为当前登录用户
        Pet pet = adoptOrder.getPet();
        pet.setState(1);
        pet.setUser(adoptOrder.getUser());
        pet.setUser_id(adoptOrder.getUser().getId());
        petMapper.update(pet);

        //6.添加一个支付单
        PayBill payBill = getPayBill(adoptOrder);
        payBillMapper.save(payBill);

        //7.完成支付
        String htmlStr = null;
        if(adoptOrder.getPayType() == 1){
            //银联支付
        }else if(adoptOrder.getPayType() == 2){
            //微信支付
        }else if(adoptOrder.getPayType() == 3){
            //7.调用支付宝接口，得到一个html字符串
            htmlStr = alipayService.topay(adoptOrder);
            System.out.println(htmlStr);
        }
        //8.添加定时任务
        QuartzJobInfo quartzJobInfo = getQuartzJobInfo(adoptOrder, payBill);
        quartzService.add(quartzJobInfo);

        return AjaxResult.me().setData(htmlStr);
    }



    /**
     * 取消订单
     * @param adoptOrder
     * @param payBill
     */
    @Override
    @Transactional
    public void cancelOrder(AdoptOrder adoptOrder, PayBill payBill) {
        //1.先修改支付单状态
        payBill.setState(-1);
        payBill.setUpdateTime(new Date());
        payBillMapper.update(payBill);

        //2.修改订单状态
        adoptOrder.setState(-1);
        adoptOrderMapper.update(adoptOrder);
    }

    /**
     * 创建QuartzJobInfo对象
     * @param adoptOrder
     * @param payBill
     * @return
     */
    private QuartzJobInfo getQuartzJobInfo(AdoptOrder adoptOrder, PayBill payBill) {
        QuartzJobInfo quartzJobInfo = new QuartzJobInfo();
        //jobName：业务类型~订单编号
        quartzJobInfo.setJobName(Constant.BUSINESS_TYPE_ADOPT + "~" + adoptOrder.getOrderSn());
        quartzJobInfo.setClz(CancelOrderJob.class); //任务Job
        quartzJobInfo.setFireDate(adoptOrder.getLastPayTime()); //触发时间
        //传递参数给Job类对象
        Map<String, Object> params = new HashMap<>();
        params.put("adoptOrder", adoptOrder);
        params.put("payBill", payBill);
        quartzJobInfo.setParams(params);
        return quartzJobInfo;
    }


    /**
     * 创建支付单对象
     * @param adoptOrder
     * @return
     */
    private PayBill getPayBill(AdoptOrder adoptOrder) {
        PayBill payBill = new PayBill();
        payBill.setDigest(adoptOrder.getDigest());      //订单摘要
        payBill.setMoney(adoptOrder.getPrice());        //支付金额
        payBill.setOrderSn(adoptOrder.getOrderSn());    //订单编号
        payBill.setLastPayTime(adoptOrder.getLastPayTime());    //最迟支付时间
        payBill.setPayChannel(adoptOrder.getPayType()); //支付渠道
        payBill.setBusinessType(Constant.BUSINESS_TYPE_ADOPT);       //业务类型
        payBill.setBusinessKey(adoptOrder.getId());     //业务主键
        payBill.setUser_id(adoptOrder.getUser().getId());   //支付人 前台用户
        payBill.setNickName(adoptOrder.getUser().getUsername());    //支付人 昵称
        payBill.setShop_id(adoptOrder.getPet().getShop_id());   //商家店铺
        payBill.setShopName(adoptOrder.getPet().getShop().getName());   //店铺名称
        return payBill;
    }
}
